package com.android.xunxian.activity;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.xunxian.entry.JLTable;
import com.android.xunxian.entry.JWdu;
import com.android.xunxian.entry.JWdu1;
import com.android.xunxian.entry.Xunx;
import com.android.xunxian.utils.UConstants;
import com.android.xunxian.utils.Util;
import com.android.xunxian.view.ActionSheetDialog;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.google.gson.Gson;
import com.oa.android.MyApplication;
import com.oa.android.R;
import com.oa.android.utils.ImageUtlis;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.db.sqlite.WhereBuilder;
import org.xutils.ex.DbException;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;

/**
 * Created by zouqh on 2016/7/9.
 */
public class DeilstXunxActivity extends Activity implements View.OnClickListener {

    @InjectView(R.id.close)
    ImageView close;
    @InjectView(R.id.title_text)
    TextView titleText;
    @InjectView(R.id.ritgh_icon)
    ImageView ritghIcon;
    @InjectView(R.id.ritgh_text)
    TextView ritghText;
    @InjectView(R.id.planTitle)
    TextView planTitle;
    @InjectView(R.id.scxPerson)
    TextView scxPerson;
    @InjectView(R.id.scxTime)
    TextView scxTime;
    @InjectView(R.id.xcxPerson)
    TextView xcxPerson;
    @InjectView(R.id.cxTime)
    TextView cxTime;
    @InjectView(R.id.zhouq)
    TextView zhouq;
    @InjectView(R.id.state)
    TextView state;
    @InjectView(R.id.code)
    TextView code;
    @InjectView(R.id.content)
    TextView content;
    @InjectView(R.id.img)
    TextView img;
    @InjectView(R.id.sp)
    TextView sp;
    @InjectView(R.id.beizhu)
    TextView beizhu;
    @InjectView(R.id.luyin)
    TextView luyin;
    @InjectView(R.id.layout)
    LinearLayout layout;
    @InjectView(R.id.myScrollView)
    ScrollView myScrollView;
    @InjectView(R.id.start)
    TextView start;
    @InjectView(R.id.stop)
    TextView stop;
    @InjectView(R.id.layout1)
    LinearLayout layout1;
    private Xunx xunx;
    private List<Xunx> xunxList;

    public String longitude;
    public String latitude;
    private LocationClientOption.LocationMode tempMode = LocationClientOption.LocationMode.Hight_Accuracy;
    private String tempcoor = "bd09ll";
    public LocationClient mLocationClient = null;
    public MyLocationListenner myListener = new MyLocationListenner();
    private String imgPath;
    private String fileName;
    private String type;
    private Dialog Jdialog;
    private String time;

    private boolean flag;
    private Util util;
    private String  updateOff;
    private String logPath;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.xunxian_diect_activity);
        ButterKnife.inject(this);
        close.setOnClickListener(this);
        titleText.setText("巡线详情");

        ritghText.setOnClickListener(this);
        img.setOnClickListener(this);
        sp.setOnClickListener(this);
        beizhu.setOnClickListener(this);
        luyin.setOnClickListener(this);
        start.setOnClickListener(this);
        stop.setOnClickListener(this);
        util=new Util(this);
        updateOff=util.getUser("off");
        logPath=Environment.getExternalStorageDirectory().getAbsolutePath() + "/xunxian/";
        xunx = (Xunx) getIntent().getSerializableExtra("xunx");
        imgPath = Environment.getExternalStorageDirectory().getPath()
                + File.separator + "Xunxian" + File.separator + xunx.getID() + File.separator;
        if (xunx != null) {
            scxPerson.setText("" + xunx.getSCXXY());
            scxTime.setText("上次巡线时间：" + xunx.getSCRQ());
            xcxPerson.setText("" + xunx.getXCXXY());
            cxTime.setText("下次巡线时间：" + xunx.getXCRQ());
            zhouq.setText("" + xunx.getSPLANZQ());
            state.setText("" + xunx.getSPLANZT());
            code.setText("巡线编码：" + xunx.getBM());
            content.setText("" + xunx.getPLANNR());
            planTitle.setText(" "+xunx.getNAME());
            ritghText.setVisibility(View.VISIBLE);
            ritghText.setText("地图");
            if (xunx.getSPLANZT().equals("未开始")) {
//           ritghText.setText("开始");

                ritghText.setVisibility(View.VISIBLE);
                layout1.setVisibility(View.VISIBLE);
                try {
                    select();
                } catch (Exception e) {
                    e.printStackTrace();
                    flag=true;
                }
            } else if (xunx.getSPLANZT().equals("执行中")) {
                layout1.setVisibility(View.VISIBLE);
                ritghText.setVisibility(View.VISIBLE);
                start.setText("执行中");
//                ritghText.setText("轨迹");
                try {
                    select();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                xcxPerson.setText("巡线人：" + xunx.getXCXXY());
                layout.setVisibility(View.VISIBLE);
                mLocationClient = new LocationClient(this);
                mLocationClient.registerLocationListener(myListener);
                setLocationOption();
                mLocationClient.start();// 启动定位
            }


        }


    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.close:
                finish();
                break;

            case R.id.ritgh_text:

                    //打开地图
                    Intent intent = new Intent(this, MapActivity.class);
                    intent.putExtra("la", latitude);
                    intent.putExtra("lo", longitude);
                intent.putExtra("xunId",xunx.getID());
                intent.putExtra("jx", xunx.getXXQY());
                    startActivity(intent);

                break;

            case R.id.img:
                Log.i("AAAAAAAAAAAAAAAAA", "拍照保存照片");
//                saveImg();
                type = "照片";

                showPickDialog();


                break;

            case R.id.sp:
                Log.i("AAAAAAAAAAAAAAAAA", "视频录像保存");
                type = "视频";

                showVdioDialog();
                break;

            case R.id.beizhu:
                Intent intenta = new Intent(this, RemarksActivity.class);
                intenta.putExtra("id", xunx.getID());
                startActivityForResult(intenta, 3);
                break;


            case R.id.luyin:
                Intent intent1 = new Intent(this, LuyinActivity.class);
                intent1.putExtra("id", xunx.getID());
                startActivityForResult(intent1, 4);
                break;

            case R.id.start:
                if(xunx.getSPLANZT().equals("未开始")){
                    if (flag){
                        tsDialog("你确定开始该条路线吗？",1);

                    }else{
                        Toast.makeText(this,"一次只能执行一条巡线",10).show();
                    }

                }else if(xunx.getSPLANZT().equals("执行中")){
                    Toast.makeText(this,"路线已经在执行中",10).show();
                }
                break;

            case R.id.stop:

               if(xunx.getSPLANZT().equals("未开始")){
                   Toast.makeText(this,"路线还没有开始",10).show();
               }else if(xunx.getSPLANZT().equals("执行中")){
                   try {
                       List<JLTable> list = MyApplication.dbManager.selector(JLTable.class).where("id","=",xunx.getID()).findAll();
                       if(list!=null&&list.size()>0){
                           finishDialog("您还有文件没有上传,是否结束路线？");
                       }else{
                           Log.i("AAAAAAAAAA","没有文件啦");
                           tsDialog("你确定结束该条路线吗？",2);
                       }
                   } catch (DbException e) {
                       e.printStackTrace();
                   }


               }
                break;


        }
    }



    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    pointDialog("请输入文件说明", 1);
                    break;
            }
        }
    };

    private void select() throws Exception {
        xunxList = MyApplication.dbManager.selector(Xunx.class).where("SPLANZT", "=", "执行中").findAll();
        if (xunxList != null && xunxList.size() > 0) {
            flag=false;
            xunx.setXXId(xunxList.get(0).getXXId());
            System.out.println("---===-"+xunxList.get(0));
        } else {
            flag=true;
            System.out.println("============="+xunx.getXXId());
        }
    }

    // //////////////////////////定位\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
    private void setLocationOption() {
        LocationClientOption option = new LocationClientOption();
        // TODO Auto-generated method stub
        option.setLocationMode(tempMode);// 可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        option.setCoorType(tempcoor);// 可选，默认gcj02，设置返回的定位结果坐标系，
        int span = 1000 * UConstants.TIME;
        System.out.println("span==="+span);
        option.setScanSpan(span);// 可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
        option.setIsNeedAddress(false);// 可选，设置是否需要地址信息，默认不需要
        option.setOpenGps(true);// 可选，默认false,设置是否使用gps
        option.setLocationNotify(false);// 可选，默认false，设置是否当gps有效时按照1S1次频率输出GPS结果
        option.setIgnoreKillProcess(true);// 可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死
        option.setEnableSimulateGps(false);// 可选，默认false，设置是否需要过滤gps仿真结果，默认需要
        option.setIsNeedLocationDescribe(true);// 可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
        option.setIsNeedLocationPoiList(false);// 可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
        mLocationClient.setLocOption(option);

    }

    public class MyLocationListenner implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation arg0) {
            // TODO Auto-generated method stub
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
            if (arg0 != null) {
            String time = dateFormat.format(new Date());

            longitude = arg0.getLongitude() + "";
            latitude = arg0.getLatitude() + "";
            // handler.sendEmptyMessage(1);
//                mLocationClient.stop();
            Log.i("longitude==", longitude);
            Log.i("time==", time);
            JWdu jWdu = new JWdu();
            jWdu.setLatitude(latitude);
            jWdu.setLongitude(longitude);
            jWdu.setXXId(xunx.getXXId());
                jWdu.setXunId(xunx.getID());
            jWdu.setTime(time);
                JWdu1 jWdu1=new JWdu1();
                jWdu1.setLatitude(latitude);
                jWdu1.setLongitude(longitude);
                jWdu1.setXXId(xunx.getXXId());
                jWdu1.setTime(time);
            try {
                MyApplication.dbManager.saveOrUpdate(jWdu);
                MyApplication.dbManager.saveOrUpdate(jWdu1);
                List<JWdu1> list = MyApplication.dbManager.selector(JWdu1.class).findAll();
                if (list != null && list.size() > 0) {
                    Log.i("list==size", list.size() + "");
                    Gson gson = new Gson();
                    String json=gson.toJson(list);//将更新数组
                    String str="{\"success\":\"true\", \"rows\":"+json+"}";
                    Log.i("list==size", str);
                    util.writeTxtToFile(str,logPath,"xunxianLog.txt");
                    updateGPS(str);
                }
            } catch (DbException e) {
                e.printStackTrace();
            }

            }
        }

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mLocationClient != null && mLocationClient.isStarted()) {
            mLocationClient.stop();
        }

    }


    /**
     * 提示
     */
    private void pointDialog(String str, int flag) {
        LayoutInflater inflaterDl = LayoutInflater.from(this);
        View layout = inflaterDl.inflate(R.layout.exti_dialog_x,
                null);
        // 对话框
        Jdialog = new Dialog(this);
        Jdialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        Jdialog.show();

        Jdialog.setContentView(layout);
        TextView sure = (TextView) layout.findViewById(R.id.sureExti);
        TextView cancle = (TextView) layout.findViewById(R.id.cancleExti);
        TextView dialogTitle = (TextView) layout.findViewById(R.id.dialogTitle);
        final EditText text = (EditText) layout.findViewById(R.id.text);
        dialogTitle.setText(str);
        sure.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
//				ContextUtil.getInstance().finishApp();
                saveJL(text.getText().toString());
                Log.i("文件记录保存完成", "============");
                Jdialog.cancel();


            }
        });
        cancle.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                saveJL(text.getText().toString());
                Log.i("文件记录保存完成", "============");
                Jdialog.cancel();
            }
        });

    }


    /**
     * 文件是否是否上传完成提示
     */
    private void finishDialog(String str) {
        LayoutInflater inflaterDl = LayoutInflater.from(this);
        View layout = inflaterDl.inflate(R.layout.exti_dialog_x,
                null);
        // 对话框
        final Dialog   dialog = new Dialog(this);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.show();

        dialog.setContentView(layout);
        TextView sure = (TextView) layout.findViewById(R.id.sureExti);
        sure.setText("是");
        TextView cancle = (TextView) layout.findViewById(R.id.cancleExti);
        cancle.setText("否");
        TextView dialogTitle = (TextView) layout.findViewById(R.id.dialogTitle);
        final EditText text = (EditText) layout.findViewById(R.id.text);
        text.setVisibility(View.GONE);
        dialogTitle.setText(str);
        sure.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
//

                dialog.cancel();
                start("2");


            }
        });
        cancle.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                dialog.cancel();
            }
        });

    }


    /**
     * 是否开始或结束
     */
    private void tsDialog(String str, final int tb) {
        LayoutInflater inflaterDl = LayoutInflater.from(this);
        View layout = inflaterDl.inflate(R.layout.exti_dialog_x,
                null);
        // 对话框
        final Dialog   dialog = new Dialog(this);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.show();

        dialog.setContentView(layout);
        TextView sure = (TextView) layout.findViewById(R.id.sureExti);
        sure.setText("是");
        TextView cancle = (TextView) layout.findViewById(R.id.cancleExti);
        cancle.setText("否");
        TextView dialogTitle = (TextView) layout.findViewById(R.id.dialogTitle);
        final EditText text = (EditText) layout.findViewById(R.id.text);
        text.setVisibility(View.GONE);
        dialogTitle.setText(str);
        sure.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
//

                dialog.cancel();
                start(tb+"");


            }
        });
        cancle.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                dialog.cancel();
            }
        });

    }

    private void saveJL(String str) {
        JLTable jlTable = new JLTable();
        jlTable.setLatitude(latitude);
        jlTable.setLongitude(longitude);
        jlTable.setId(xunx.getID());
        jlTable.setXXId(xunx.getXXId());
        jlTable.setFileKind(type);
        jlTable.setFileDt(time);
        jlTable.setFileName(fileName);
        jlTable.setFileMemo(str);
        try {
            MyApplication.dbManager.save(jlTable);

        } catch (DbException e) {
            e.printStackTrace();
        }

        if (Util.NoNull(updateOff)&&updateOff.equals("1")){
            upDate(jlTable);
        }

    }

    //保存图片
    private void saveImg() {
        if (Environment.MEDIA_MOUNTED.equals(Environment
                .getExternalStorageState())) {
            Date nowTime = new Date();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
                    "yyyyMMddHHmmss");
            time = simpleDateFormat.format(nowTime);
            fileName = xunx.getID() + "_" + time + ".jpg";
            Log.e("picPath--------", imgPath + fileName);
            if (!new File(imgPath).exists()) {
                new File(imgPath).mkdirs();// 创建文件夹
            }
//
            Intent openCameraIntent = new Intent(
                    MediaStore.ACTION_IMAGE_CAPTURE);
            Uri imageUri = Uri.fromFile(new File(imgPath + fileName));
            // 指定照片保存路径（SD卡），image.jpg为一个临时文件，每次拍照后这个图片都会被替换
            openCameraIntent
                    .putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
            startActivityForResult(openCameraIntent, 1);
        } else {
            Toast.makeText(this, "请先安装好sd卡",
                    Toast.LENGTH_SHORT).show();
        }
    }

    //录制视频
    private void saveVodie() {
        Intent intent = new Intent();
        intent.setAction("android.media.action.VIDEO_CAPTURE");
        intent.addCategory("android.intent.category.DEFAULT");

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
                "yyyyMMddHHmmss");
        time = simpleDateFormat.format(new Date());
        fileName = xunx.getID() + "_" + time + ".MP4";
        File file = new File(imgPath + fileName);
        if (file.exists()) {
            file.delete();
        }
        Uri uri = Uri.fromFile(file);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        startActivityForResult(intent, 2);
    }

    private Uri mPhotoUri = null;

    //选择图片
    void showPickDialog() {
        new ActionSheetDialog(this)
                .builder()
                .setCancelable(true)
                .setCanceledOnTouchOutside(true)
                .addSheetItem("相机拍照", ActionSheetDialog.SheetItemColor.Blue,
                        new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {

                                new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        saveImg();
                                    }
                                }).start();

                            }
                        })
                .addSheetItem("相册选择", ActionSheetDialog.SheetItemColor.Blue,
                        new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                Intent intent = new Intent(Intent.ACTION_PICK,
                                        null);
                                intent.setDataAndType(
                                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                                        "image/*");
                                startActivityForResult(intent,
                                        5);
                            }
                        }).show();
    }


    //选择视频
    void showVdioDialog() {
        new ActionSheetDialog(this)
                .builder()
                .setCancelable(true)
                .setCanceledOnTouchOutside(true)
                .addSheetItem("开始录像", ActionSheetDialog.SheetItemColor.Blue,
                        new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {

                                saveVodie();

                            }
                        })
                .addSheetItem("选择录像", ActionSheetDialog.SheetItemColor.Blue,
                        new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                Intent intent = new Intent(Intent.ACTION_GET_CONTENT,
                                        null);
                                intent.setDataAndType(
                                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                                        "video/*");
                                startActivityForResult(intent,
                                        6);
                            }
                        }).show();
    }





    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 1) {
            if (resultCode == Activity.RESULT_OK) {
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inSampleSize = 2;// 图片宽高都为原来的二分之一，即图片为原来的四分之一
                Bitmap bitmap = BitmapFactory.decodeFile(
                        imgPath + fileName, options);
                FileOutputStream b = null;
                try {
                    b = new FileOutputStream(imgPath + fileName);
                    if (b != null) {
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件
                        handler.sendEmptyMessage(1);
                    }

                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        if (b != null) {
                            b.flush();
                            b.close();
                            bitmap.recycle();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        } else if (requestCode == 2) {
            if (data != null)
                handler.sendEmptyMessage(1);
        } else if (requestCode == 3) {
            Log.i("DeilstXunxActivity===", "保存备注");
            if (data != null) {
                time = data.getStringExtra("time");
                fileName = data.getStringExtra("name");
                type = "备注";
                handler.sendEmptyMessage(1);
            }

        } else if (requestCode == 4) {
            Log.i("DeilstXunxActivity===", "保存备注");
            if (data != null) {
                time = data.getStringExtra("time");
                fileName = data.getStringExtra("name");
                type = "录音";
                handler.sendEmptyMessage(1);
            }

        } else if (requestCode == 5) {
            Log.i("DeilstXunxActivity===", "相册选择");
            if (data != null) {


                Uri uri = data.getData();
                String  path= ImageUtlis.getRealPathFromUri(this,uri);
                if (null==path||path.length()<=0){
                    Toast.makeText(this,"获取文件失败",Toast.LENGTH_SHORT).show();
                    return;
                }


                Date nowTime = new Date();
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
                        "yyyyMMddHHmmss");
                time = simpleDateFormat.format(nowTime);
                fileName = xunx.getID() + "_" + time + ".jpg";
                Log.e("picPath--------", imgPath + fileName);
                if (!new File(imgPath).exists()) {
                    new File(imgPath).mkdirs();// 创建文件夹
                }
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inSampleSize = 2;// 图片宽高都为原来的二分之一，即图片为原来的四分之一
                Bitmap bitmap = BitmapFactory.decodeFile(
                        path, options);

                FileOutputStream b = null;
                try {
                    b = new FileOutputStream(imgPath + fileName);
                    if (b != null) {
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件
                        handler.sendEmptyMessage(1);
                    }

                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        if (b != null) {
                            b.flush();
                            b.close();
                            bitmap.recycle();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            } else {

            }


        } else if (requestCode == 6) {

            if (data != null) {

                Uri uri = data.getData();
                String  path= ImageUtlis.getRealPathFromUri(this,uri);
                if (null==path||path.length()<=0){
                    Toast.makeText(this,"获取文件失败",Toast.LENGTH_SHORT).show();
                    return;
                }

                Log.i("DeilstXunxActivity===", path);
                Date nowTime = new Date();
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
                        "yyyyMMddHHmmss");
                time = simpleDateFormat.format(nowTime);
                fileName = xunx.getID() + "_" + time + ".MP4";
                Log.e("picPath--------", imgPath + fileName);
                copyfile(new File(path), new File(imgPath + fileName), true);
                handler.sendEmptyMessage(1);
            }
        }
    }


    public static void copyfile(File fromFile, File toFile, Boolean rewrite)

    {

        if (!fromFile.exists()) {

            return;

        }

        if (!fromFile.isFile()) {

            return;

        }

        if (!fromFile.canRead()) {
            return;

        }

        if (!toFile.getParentFile().exists()) {

            toFile.getParentFile().mkdirs();

        }

        if (toFile.exists() && rewrite) {

            toFile.delete();

        }

        //当文件不存时，canWrite一直返回的都是false


        try {

            FileInputStream fosfrom = new FileInputStream(fromFile);

            FileOutputStream fosto = new FileOutputStream(toFile);

            byte bt[] = new byte[1024];

            int c;

            while ((c = fosfrom.read(bt)) > 0) {

                fosto.write(bt, 0, c); //将内容写到新文件当中

            }

            fosfrom.close();

            fosto.close();

        } catch (Exception ex) {

            Log.e("readfile", ex.getMessage());

        }

    }

    ProgressDialog dialog;

    //路线开始或者结束
    private void start(final String mar) {
        dialog = ProgressDialog.show(this, null, "请稍等...", true, false);
        RequestParams params = new RequestParams(UConstants.START_AND_STOP);
        params.addBodyParameter("LKind", "CBJ");
        params.addBodyParameter("EmpId", UConstants.EmpId);
        params.addBodyParameter("PlanId", xunx.getID());
        params.addBodyParameter("BMark", mar);
//
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Util.printLog("getMerchants------------onSuccess-----", result);
                if (result.length() > 0) {
                    try {
                        JSONObject object = new JSONObject(result);
                        boolean success = object.getBoolean("success");
                        String msg = object.getString("msg");
                        if (success) {
                            if(mar.equals("1")){
                                xunx.setXXId(msg);
                                xunx.setSPLANZT("执行中");
//                                start.setText("执行中");
                                state.setText("执行中");
                                xunx.setXCXXY(UConstants.EmpName);
                                xcxPerson.setText("巡线人：" + UConstants.EmpName);
                                XunxActivity1.activity1.refsh();
                                layout.setVisibility(View.VISIBLE);
                                mLocationClient = new LocationClient(DeilstXunxActivity.this);
                                mLocationClient.registerLocationListener(myListener);
                                setLocationOption();
                                mLocationClient.start();// 启动定位
                                Toast.makeText(x.app(), "巡线开始", Toast.LENGTH_LONG).show();
                                try {
                                    MyApplication.dbManager.saveOrUpdate(xunx);
                                    Util.printLog("save---xunx----","success"+xunx.getID());
                                } catch (DbException e) {

                                    e.printStackTrace();
                                    Util.printLog("save---xunx----DbException",e.getMessage());
                                }
                            }else if(mar.equals("2")){
                                xunx.setSPLANZT("已完成");
                                start.setText("已完成");
                                layout.setVisibility(View.GONE);
                                layout1.setVisibility(View.GONE);
                                XunxActivity1.activity1.refsh();
                                try {
                                    MyApplication.dbManager.delete(JWdu.class);
                                 List<Xunx>   list = MyApplication.dbManager.selector(Xunx.class).where("SPLANZT", "=", "执行中").findAll();
                                    if(list!=null&&list.size()>0){
                                      Xunx xx = list.get(0);
                                        xx.setSPLANZT("已完成");
                                        MyApplication.dbManager.saveOrUpdate(xx);
                                    }
                                } catch (DbException e) {
                                    e.printStackTrace();
                                }
                                Toast.makeText(x.app(), "成功结束", Toast.LENGTH_LONG).show();
                            }


                        }else{
                            Toast.makeText(x.app(), msg, Toast.LENGTH_LONG).show();
                        }


                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                dialog.dismiss();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Util.printLog("getMerchants------------onError-----", ex.getMessage() + "");

                Toast.makeText(x.app(), "地址错误或服务器无法连接！", Toast.LENGTH_LONG).show();
                dialog.dismiss();
            }

            @Override
            public void onCancelled(CancelledException cex) {

                Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show();
                Util.printLog("getMerchants------------onCancelled-----", cex.getMessage() + "");
                dialog.dismiss();
            }

            @Override
            public void onFinished() {

            }
        });
    }




    //上传路线
    private void updateGPS(final String mar) {
//        dialog = ProgressDialog.show(this, null, "上传中...", true, false);
        RequestParams params = new RequestParams(UConstants.UPDATE_GPS);
        params.addBodyParameter("LKind", "CBJ");
        params.addBodyParameter("EmpId", UConstants.EmpId);
        params.addBodyParameter("Data", mar);
//
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Util.printLog("getMerchants------------onSuccess-----", result);
                if (result.length() > 0) {
                    try {
                        JSONObject object = new JSONObject(result);
                        boolean success = object.getBoolean("success");
                        String msg = object.getString("msg");
                        if (success) {
                            try {
                                MyApplication.dbManager.delete(JWdu1.class);
                            } catch (DbException e) {
                                e.printStackTrace();
                            }
                        }


                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Util.printLog("getMerchants------------onError-----", ex.getMessage() + "");

                Toast.makeText(x.app(), "地址错误或服务器无法连接！", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onCancelled(CancelledException cex) {

                Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show();
                Util.printLog("getMerchants------------onCancelled-----", cex.getMessage() + "");
            }

            @Override
            public void onFinished() {

            }
        });
    }



    //获取巡线列表
    private void upDate(final JLTable jl) {
        if (jl==null){
            return;
        }
        dialog = ProgressDialog.show(this, null, "上传中...", true, false);
//

        if (!new File(imgPath+jl.getFileName()).exists()){
            dialog.dismiss();
            Toast.makeText(x.app(), "文件不存在！", Toast.LENGTH_SHORT).show();
            return;
        }

        List<JLTable> jlTableList=new ArrayList<>();
        jlTableList.add(jl);
        Gson gson = new Gson();
        String json1=gson.toJson(jlTableList);//将更新数组
        Log.i("BBBBBBBBBBBBBB",json1);
        String info  ="{\"success\":\"true\", \"total\":\""+jlTableList.size()+"\",\"rows\":"+json1+"}";

        RequestParams params = new RequestParams(UConstants.XX_UPDATE);
//
        params.addBodyParameter("LKind","CBJ");
        params.addBodyParameter("EmpId",UConstants.EmpId);
        params.addBodyParameter("PartId", UConstants.PartId );
        params.addBodyParameter("FileInfo",info);

            params.addBodyParameter("FILES", new File(imgPath+jl.getFileName()));



        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Util.printLog("getMerchants------------onSuccess-----", result);
                if (result.length() > 0) {
                    try {
                        JSONObject object = new JSONObject(result);
//                        allPage = Integer.parseInt(object.getString("total"));
//                        allPage = (int) Math.ceil((double) allPage / pageSize);
                        boolean success = object.getBoolean("success");
//                        String msg = object.getString("msg");
                        if (success) {
                            Toast.makeText(x.app(), "上传成功！", Toast.LENGTH_SHORT).show();

                                new File(imgPath+jl.getFileName()).delete();
                                WhereBuilder b = WhereBuilder.b();
                                b.and("FileName","=",jl.getFileName()); //构造修改的条件
                                try {
                                    MyApplication.dbManager.delete(JLTable.class,b);
                                } catch (DbException e) {
                                    e.printStackTrace();
                                }


                        } else {
                            Toast.makeText(x.app(), "上传失败,请手动上传！", Toast.LENGTH_SHORT).show();
                        }
//                        Toast.makeText(x.app(), msg, Toast.LENGTH_LONG).show();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                dialog.dismiss();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Util.printLog("getMerchants------------onError-----", ex.getMessage() + "");

                Toast.makeText(x.app(), "上传失败,请手动上传！", Toast.LENGTH_LONG).show();
                dialog.dismiss();
            }

            @Override
            public void onCancelled(CancelledException cex) {

                Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show();
                Util.printLog("getMerchants------------onCancelled-----", cex.getMessage() + "");
                dialog.dismiss();
            }

            @Override
            public void onFinished() {

            }
        });
    }
}
